package game.module.mail.logic;

import game.entity.Hero;
import game.module.mail.bean.MailList;
import game.module.mail.bean.MailList.MailItem;
import game.module.mail.dao.MailDao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class MailManager {

	@Autowired
	private MailDao mailDao;

	@Async
	public void asyncSendMail(MailItem mailItem) {
		int toRoleId = mailItem.getReceiverId();
		MailList mailList = mailDao.getMails(toRoleId);
		if (mailList == null) {
			mailDao.initMail(toRoleId);
			mailList = new MailList();
		}
		List<MailItem> mailAll = mailList.getMailAllList();
		if (mailAll == null) {
			mailAll = new ArrayList<MailItem>();
			mailList.setMailAllList(mailAll);
		}
		// 设置id
		if (mailAll.size() == 0) {
			mailItem.setId(1);
		} else {
			MailItem lastItem = mailAll.get(mailAll.size() - 1);
			mailItem.setId(lastItem.getId() + 1);
		}
		mailAll.add(mailItem);
		mailDao.saveMail(toRoleId, mailList);
		// TODO 给玩家发送新邮件提示消息
	}

	@Async
	public void asyncRemoveMail(Hero hero, int mailId) {
		MailList mailList = mailDao.getMails(hero.getId());
		if (mailList == null || mailList.getMailAllList() == null) {
			return;
		}
		Iterator<MailItem> mailItemIte = mailList.getMailAllList().iterator();
		while (mailItemIte.hasNext()) {
			MailItem mailItem = mailItemIte.next();
			if (mailItem.getId() == mailId) {
				mailItemIte.remove();
			}
		}
		mailDao.saveMail(hero.getId(), mailList);
		// 给玩家发送删除邮件提示消息
	}

	@Async
	public void listMail(Hero hero, short nowPage, short size) {
		List<MailItem> ret = new ArrayList<MailItem>();
		MailList mailList = mailDao.getMails(hero.getId());
		if (mailList == null || mailList.getMailAllList() == null) {
			return;
		}
		List<MailItem> mailAll = mailList.getMailAllList();
		Collections.sort(mailList.getMailAllList(), new MailNewToOldComparator());
		int startIndex = (nowPage - 1) * size;
		for (int i = startIndex; i < nowPage * size && i < mailAll.size(); i++) {
			ret.add(mailAll.get(i));
		}
		//处理ret
	}

	@Async
	public void getMailItem(int heroId, int mailId) {
		MailItem ret;
		MailList mailList = mailDao.getMails(heroId);
		if (mailList == null || mailList.getMailAllList() == null) {
			return;
		}
		for (MailItem mailItem : mailList.getMailAllList()) {
			if (mailId == mailItem.getId()) {
				ret = mailItem;
			}
		}
		//处理ret
	}
}
